package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.domain.*;
import com.itheima.youdianda.dto.UserInfo;
import com.itheima.youdianda.service.*;
import com.itheima.youdianda.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName UserController
 * @Description 用户登录控制器
 * @Author Young
 * @Date 2023/2/11 14:07
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/index")
public class SysUserContorller {

    @Value("${YouDianDa.salt}")
    private String salt;//读取固定的盐值
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysConfigService sysconfigService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private YddCateService yddCateService;
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddAdvposService yddAdvposService;
    @Autowired
    private YddTagService yddTagService;
    @Autowired
    private YddAdvimgService yddAdvimgService;
    @Autowired
    private YddUserService yddUserService;

    /**
     * 后台系统登录
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<Map> login(@RequestBody Map map){
        log.info("接收到用户登录的请求: {}",map);
        //获取登录信息
        String loginName = (String) map.get("login_name");
        String password = (String) map.get("password");
        //处理发送过来的密码
        String md5Password = DigestUtils.md5DigestAsHex((password + "abc").getBytes());
        //查询用户是否存在
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getLoginName,loginName);
        SysUser user = sysUserService.getOne(query);
        //账号密码校验
        if (user != null){
            //账号存在
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getPassword,md5Password);
            SysUser one = sysUserService.getOne(queryWrapper);

            return one == null ? R.error("密码有误,请检查并重新输入 ==>>") : R.success(JwtUtils.giveToken(map));
        }else
            //账号不存在
            return R.error("账号不存在,请联系管理员 ==>>");
    }

    /**
     * 获取系统配置
     * @return
     */
    @GetMapping("/getConfig")
    public R<Map> systemConfig() {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getTabValue, "system");
        List<SysConfig> sysConfigs = sysconfigService.list(wrapper);

        HashMap<String, String> map = new HashMap<>();
        for (SysConfig sysConfig : sysConfigs) {
            map.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
        }

        return R.success(map);

    }


    /**
     * 用户、菜单、字典, 等配置信息查询
     * @param request
     * @return
     */
    @PostMapping("/profile")
    public R<Map> profile(HttpServletRequest request) {
        //获取前端的token
        String token = request.getHeader("x-token");
        //解析拿到Claims
        Claims claims = JwtUtils.getClaims(token);
        //{login_name=admin, password=111111, exp=1676194138}
        String loginName = (String) claims.get("login_name");
        //开始查询数据库,并封装
        //查询user表
        LambdaQueryWrapper<SysUser> SysUserWrapper = new LambdaQueryWrapper<>();
        SysUserWrapper.eq(SysUser::getLoginName,loginName);
        SysUser user = sysUserService.getOne(SysUserWrapper);
        //查询角色表
        LambdaQueryWrapper<SysRole> SysRoleWrapper = new LambdaQueryWrapper<>();
        SysRoleWrapper.eq(SysRole::getId,user.getRoleId());
        SysRole sysRole = sysRoleService.getOne(SysRoleWrapper);
        //以上两表合并 返回==> userInfo
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user,userInfo);
        userInfo.setRoleName(sysRole.getName());

        //封装 menuList(菜单列表)
        LambdaQueryWrapper<SysRoleMenu> SysRoleMenuWrapper = new LambdaQueryWrapper<>();
        //根据用户角色ID, 查询出对应的菜单ID对应的数据, 分装成集合
        SysRoleMenuWrapper.eq(SysRoleMenu::getRoleId,userInfo.getRoleId());
        List<SysRoleMenu> list = sysRoleMenuService.list(SysRoleMenuWrapper);
        List idList=list.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        //根据菜单ID, 查询出菜单对象, 放到集合中==>>返回出去
//        List<SysMenu> sysMenus = sysMenuService.listByIds(idList);
        LambdaQueryWrapper<SysMenu> sysMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysMenuLambdaQueryWrapper.eq(SysMenu::getType, 1);
        sysMenuLambdaQueryWrapper.eq(SysMenu::getIsShow, 1);
        sysMenuLambdaQueryWrapper.in(SysMenu::getId, idList);
        List<SysMenu> sysMenus = sysMenuService.list(sysMenuLambdaQueryWrapper);


        //封装dictsList (数据字典)
        //先给dicts分组
        LambdaQueryWrapper<SysDict> sysDictWrapper = new LambdaQueryWrapper<>();
        sysDictWrapper.select(SysDict::getType).groupBy(SysDict::getType);
        //按类型分组, 获取到所有的类型
        List<Object> dictTypes = sysDictService.listObjs(sysDictWrapper);
        //准备容器
        Map<String, Map<String,String>> newList = new HashMap<>();
        //操作每种类型
        for (Object type : dictTypes) {
            Map<String, String> map = new HashMap<>();
            sysDictWrapper = new LambdaQueryWrapper<>();
            //根据类型(type)查询出, 对应的一条记录, 封装成对象
            sysDictWrapper.eq(SysDict::getType,type);
            List<SysDict> dicts = sysDictService.list(sysDictWrapper);
            //遍历拿到的对象, 进行装配
            for (SysDict sysDict : dicts) {
                //拿到Value  对应的Labe
                map.put(sysDict.getValue(),sysDict.getLabel());
            }

            // 最后封装 返回==>>type : {"0": "单表","1": "主表"}, 访问外层大map
            newList.put((String)type,map);
        }

        //btnList
        Map btnList = new HashMap<>();
        btnList.put("btnList","*");

        //打包数据 == 发送
        Map map = new HashMap();
        map.put("userInfo",userInfo);
        map.put("menuList",sysMenus);
        map.put("dictsList",newList);
        map.put("btnList",btnList);

        return R.success(map);
    }

    /**
     * 主页统计信息
     * @param request
     * @return
     */
    @GetMapping("/baseInfo")
    public R<Map> baseInfo(HttpServletRequest request){
        //获取前端的token
        String token = request.getHeader("x-token");
        //解析拿到Claims        {login_name=admin, password=111111, exp=1676222884}
        Claims claims = JwtUtils.getClaims(token);
        //查询 分类数据 拿到每种分类的各个对象
        List<YddCate> yddCateList = yddCateService.list();
        //遍历处理yddCateList
        List<YddCate> cates = yddCateList.stream().map(item -> {
            //获取每种分类对象的id
            Integer cateId = item.getId();
            LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YddArticle::getCateid, cateId);
            int count = yddArticleService.count(queryWrapper);
            item.setSortNum(count);
            return item;
        }).collect(Collectors.toList());
        HashMap<String,Object> map = new HashMap<>();
        map.put("all_cate",cates);
        //分类总数
        Integer cateCount = yddCateService.count();
        map.put("cate_num",cateCount);
        //广告图备注
        Integer advimgCount = yddAdvimgService.count();
        map.put("advimg_num",advimgCount);
        //广告位总数
        Integer count = yddAdvposService.count();
        map.put("advpos_num",count);
        //标签的总数
        Integer tagCount = yddTagService.count();
        map.put("tag_num",tagCount);
        //管理员数量
        Integer userCount = sysUserService.count();
        map.put("admin_num",userCount);
        //文章总数
        Integer articleCount = yddArticleService.count();
        map.put("article_num",articleCount);


        LambdaQueryWrapper<YddUser> yddUserQuery = new LambdaQueryWrapper<>();
        yddUserQuery.orderByDesc(YddUser::getId).last("limit 7");
        List<YddUser> yddUserList = yddUserService.list(yddUserQuery);
        map.put("new_user",yddUserList);

        LambdaQueryWrapper<YddArticle> yddArticleQuery = new LambdaQueryWrapper<>();
        yddArticleQuery.orderByDesc(YddArticle::getLovenum).last("limit 7");
        List<YddArticle> yddArticles = yddArticleService.list(yddArticleQuery);
        map.put("hot_article",yddArticles);

        Map<String,Integer> userMap = new HashMap();
        int totalCount = yddUserService.count();
        yddUserQuery = new LambdaQueryWrapper<>();
        yddUserQuery.eq(YddUser::getSex,0);  //男的数量
        int user_man = yddUserService.count(yddUserQuery);
        int user_women = totalCount - user_man;
        userMap.put("total",totalCount);
        userMap.put("user_man",user_man);
        userMap.put("user_woman",user_women);
        map.put("user",userMap);

        return R.success(map);
    }

}
